import {
  Controller,
  Get,
  Session,
  Header,
  Query,
  Request,
} from '@nestjs/common';
import { AppService } from './app.service';
import { WechatApp } from './libs/utils';
import { WXBizDataCrypt } from './libs/WXBizDataCrypt';
import { CreateTokenDto } from './token/dto/create-token.dto';
import { TokenService } from './token/token.service';
import { Buffer } from 'buffer';

const axios = require('axios').default;

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private tokenService: TokenService,
  ) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get('api/captcha')
  @Header('content-type', 'image/svg+xml')
  async getCaptcha(@Session() session: Record<string, any>): Promise<any> {
    const captcha = await this.appService.getCaptcha();
    const { text, data } = captcha;
    session.captcha = text;
    console.log('session', session);
    return data;
  }

  @Get('api/wechat/code')
  async getWechatCode(@Query() query: any) {
    const { code } = query;

    console.log('code', code);
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${WechatApp.appId}&secret=${WechatApp.appSecret}&js_code=${code}&grant_type=authorization_code`;
    const codeData = await axios({ url });

    return codeData.data;
  }

  @Get('api/wechat/decrypt')
  async getWechatDecrypt(@Query() query: any) {
    const { sessionKey, encryptedData, iv } = query;

    console.log('decrypt', query);

    const pc = new WXBizDataCrypt(WechatApp.appId, sessionKey);
    return pc.decryptData(encryptedData, iv);
  }

  @Get('api/wechat/QR')
  async getWechatQR(@Query() query: any) {
    const { id } = query;
    const createTokenDto = new CreateTokenDto();
    createTokenDto.type = 'access';
    createTokenDto.time = String(Date.now());

    const token = await this.tokenService.createWechat(createTokenDto);

    console.log('acc token', token);

    const jsonData = JSON.stringify({
      scene: `${id}`,
      page: 'pages/detail/index',
      // env_version: 'trial',
      check_path: true,
      width: '200',
    });

    console.log('jsonData', jsonData);

    const qrImg = await axios({
      url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`,
      method: 'POST',
      responseType: 'arraybuffer',
      data: jsonData,
    });

    const { data } = qrImg;
    console.log('data', data);

    return `data:image/png;base64,${Buffer.from(data, 'utf-8').toString(
      'base64',
    )}`;
  }
}
